<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的课表</title>
    <link rel="stylesheet" href="/common/plugins/element-plus/index.css" />
    <script src="/common/plugins/iconify/iconify-icon.min.js"></script>
    <script src="/common/plugins/tailwindcss/tailwind.min.js"></script>
    <script src="/common/plugins/vue/vue.global.js"></script>
    <script src="/common/plugins/element-plus/index.full.js"></script>
    <script src="/common/plugins/axios/axios.min.js"></script>
    <script src="/common/js/axios-config.js"></script>
    <style>
        [v-cloak] {
            display: none !important;
        }
        .schedule-grid {
            display: grid;
            grid-template-columns: 100px repeat(7, 1fr);
            gap: 1px;
            background-color: #e5e7eb;
        }
        .time-slot, .day-header, .schedule-cell {
            background-color: white;
            padding: 8px;
            min-height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .schedule-cell {
            flex-direction: column;
            position: relative;
        }
        .appointment-item {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            width: 100%;
            text-align: center;
            margin: 1px 0;
            cursor: pointer;
        }
        .appointment-pending {
            background: linear-gradient(135deg, #f59e0b, #d97706);
        }
        .appointment-completed {
            background: linear-gradient(135deg, #10b981, #059669);
        }
    </style>
</head>

<body class="bg-gray-50">
<div id="app">
    <div id="page-management__my-schedule" v-cloak>
        <!-- 页面标题 -->
        <div class="mb-5">
            <h2 class="text-2xl font-bold text-gray-800 mb-2">我的课表</h2>
            <p class="text-gray-600">查看未来一周的课程安排</p>
        </div>

        <!-- 工具栏 -->
        <div class="bg-white rounded-lg shadow p-4 mb-5">
            <div class="flex justify-between items-center">
                <div class="flex items-center space-x-4">
                        <span class="text-sm text-gray-600">
                            显示时间：{{ weekStartDate }} 至 {{ weekEndDate }}
                        </span>
                    <span class="text-sm text-blue-600">
                            共 {{ scheduleData.length }} 节课程
                        </span>
                </div>
                <div class="flex items-center space-x-2">
                    <el-button size="small" @click="loadSchedule">
                        <iconify-icon icon="mdi:refresh" width="16" height="16" class="mr-1"></iconify-icon>刷新
                    </el-button>
                    <el-button size="small" @click="prevWeek">
                        <iconify-icon icon="mdi:chevron-left" width="16" height="16" class="mr-1"></iconify-icon>上一周
                    </el-button>
                    <el-button size="small" @click="nextWeek">
                        <iconify-icon icon="mdi:chevron-right" width="16" height="16" class="mr-1"></iconify-icon>下一周
                    </el-button>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-lg shadow p-4" v-loading="loading">
            <div class="schedule-grid">
                <div class="time-slot bg-gray-100 font-semibold">时间</div>

                <div v-for="day in weekDays" :key="day.date" class="day-header bg-gray-100 font-semibold">
                    <div>{{ day.dayName }}</div>
                    <div class="text-xs text-gray-500 mt-1">{{ day.date }}</div>
                </div>

                <!-- 时间段和课程 -->
                <template v-for="timeSlot in timeSlots" :key="timeSlot">
                    <!-- 时间标签 -->
                    <div class="time-slot bg-gray-50 font-medium text-sm">
                        {{ timeSlot }}
                    </div>

                    <div v-for="day in weekDays" :key="`${timeSlot}-${day.date}`" class="schedule-cell">
                        <div v-for="appointment in getAppointmentsForSlot(day.date, timeSlot)"
                             :key="appointment.id"
                             :class="getAppointmentClass(appointment)"
                             @click="viewAppointment(appointment)">
                            <div class="font-medium">
                                {{ userInfo && userInfo.role === 3 ? (appointment.studentName || appointment.student_name || '学员') : (appointment.coachName || appointment.coach_name || '教练') }}
                            </div>
                            <div class="text-xs">{{ formatTime(appointment.startTime) }}-{{ formatTime(appointment.endTime) }}</div>
                            <div class="text-xs">{{ appointment.tableNumber || appointment.table_number || appointment.tableId }}号台</div>
                        </div>
                    </div>
                </template>
            </div>

            <div v-if="!loading && scheduleData.length === 0" class="text-center py-8 text-gray-500">
                <iconify-icon icon="mdi:calendar-outline" width="48" height="48" class="mb-2"></iconify-icon>
                <p>本周暂无课程安排</p>
            </div>
        </div>

        <!-- 课程详情对话框 -->
        <el-dialog v-model="showDetailDialog" title="课程详情" width="500px">
            <div v-if="selectedAppointment" class="space-y-4">
                <div class="flex items-center">
                    <span class="w-20 text-gray-600">学员：</span>
                    <span class="font-medium">{{ selectedAppointment.studentName || '未知' }}</span>
                </div>
                <div class="flex items-center">
                    <span class="w-20 text-gray-600">时间：</span>
                    <span>{{ selectedAppointment.startTime }} 至 {{ selectedAppointment.endTime }}</span>
                </div>
                <div class="flex items-center">
                    <span class="w-20 text-gray-600">球台：</span>
                    <span>{{ selectedAppointment.tableNumber || selectedAppointment.tableId }}号台</span>
                </div>
                <div class="flex items-center">
                    <span class="w-20 text-gray-600">费用：</span>
                    <span class="text-green-600 font-semibold">¥{{ selectedAppointment.cost }}</span>
                </div>
                <div class="flex items-center">
                    <span class="w-20 text-gray-600">状态：</span>
                    <el-tag v-if="selectedAppointment.status === 0" type="warning" size="small">待确认</el-tag>
                    <el-tag v-else-if="selectedAppointment.status === 1" type="success" size="small">已确认</el-tag>
                    <el-tag v-else-if="selectedAppointment.status === 2" type="info" size="small">已完成</el-tag>
                    <el-tag v-else-if="selectedAppointment.status === 3" type="danger" size="small">已取消</el-tag>
                </div>
            </div>
            <template #footer>
                <el-button @click="showDetailDialog = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</div>

<script>
    const { createApp } = Vue;
    const { ElMessage } = ElementPlus;

    createApp({
        data() {
            return {

                loading: false,
                userInfo: null,
                currentWeekStart: new Date(),
                scheduleData: [],
                showDetailDialog: false,
                selectedAppointment: null,
                timeSlots: [
                    '08:00-09:00', '09:00-10:00', '10:00-11:00', '11:00-12:00',
                    '14:00-15:00', '15:00-16:00', '16:00-17:00', '17:00-18:00',
                    '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00'
                ]
            };
        },

        computed: {
            weekDays() {
                if (!this.currentWeekStart) return [];
                const days = [];
                for (let i = 0; i < 7; i++) {
                    const date = new Date(this.currentWeekStart);
                    date.setDate(date.getDate() + i);
                    const dayName = date.toLocaleDateString('zh-CN', { weekday: 'short' });
                    days.push({
                        date: this.formatDate(date),
                        dayName: dayName // 系统自动计算的星期名称
                    });
                }
                return days;
            },

            weekStartDate() {
                if (!this.currentWeekStart) return '';
                return this.formatDate(this.currentWeekStart);
            },

            weekEndDate() {
                if (!this.currentWeekStart) return '';
                const endDate = new Date(this.currentWeekStart);
                endDate.setDate(endDate.getDate() + 6);
                return this.formatDate(endDate);
            }
        },

        methods: {
            initCurrentWeek() {
                const now = new Date();
                const dayOfWeek = now.getDay();
                const startOfWeek = new Date(now);
                const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
                startOfWeek.setDate(now.getDate() - daysFromMonday); // 回退到周一
                startOfWeek.setHours(0, 0, 0, 0);
                this.currentWeekStart = startOfWeek;
            },
            // 加载课表数据
            async loadSchedule() {
                try {
                    this.loading = true;
                    // 获取当前用户信息
                    const userInfo = getCurrentUserInfo();
                    if (!userInfo || !userInfo.id) {
                        ElMessage.error('用户信息无效，请重新登录');
                        return;
                    }
                    this.userInfo = userInfo;
                    // 根据用户角色选择不同的API
                    const isCoach = userInfo.userRole === 3;
                    const isStudent = userInfo.userRole === 4;
                    console.log('加载课表，用户ID:', userInfo.id, '角色:', isCoach ? '教练' : '学生');
                    const apiPath = isCoach
                        ? `/appointments/coach/${userInfo.id}/schedule`
                        : `/appointments/student/${userInfo.id}/schedule`;
                    const response = await apiClient.get(apiPath);
                    console.log('课表数据响应:', response);
                    if (response.code === 200) {
                        this.scheduleData = response.data || [];
                        ElMessage.success(`加载成功，共${this.scheduleData.length}节课程`);
                    } else {
                        ElMessage.error(response.message || '加载课表失败');
                    }
                } catch (error) {
                    console.error('加载课表失败:', error);
                    ElMessage.error('加载课表失败');
                } finally {
                    this.loading = false;
                }
            },

            // 获取指定时间段的预约
            getAppointmentsForSlot(date, timeSlot) {
                return this.scheduleData.filter(appointment => {
                    const appointmentDate = this.formatDate(new Date(appointment.startTime));
                    const appointmentHour = new Date(appointment.startTime).getHours();
                    const slotHour = parseInt(timeSlot.split(':')[0]);

                    return appointmentDate === date && appointmentHour === slotHour;
                });
            },

            // 获取预约样式类
            getAppointmentClass(appointment) {
                const baseClass = 'appointment-item';
                if (appointment.status === 0) {
                    return `${baseClass} appointment-pending`;
                } else if (appointment.status === 2) {
                    return `${baseClass} appointment-completed`;
                }
                return baseClass;
            },

            // 查看预约详情
            viewAppointment(appointment) {
                this.selectedAppointment = appointment;
                this.showDetailDialog = true;
            },

            // 格式化日期
            formatDate(date) {
                if (!date) return '';
                return date.toISOString().split('T')[0];
            },
            // 格式化时间
            formatTime(dateTimeStr) {
                if (!dateTimeStr) return '';
                return new Date(dateTimeStr).toTimeString().slice(0, 5);
            },

            // 上一周
            prevWeek() {
                const newWeekStart = new Date(this.currentWeekStart);
                newWeekStart.setDate(newWeekStart.getDate() - 7);
                this.currentWeekStart = newWeekStart;  // 赋值新对象触发响应式
                this.loadSchedule();
            },
            nextWeek() {
                const newWeekStart = new Date(this.currentWeekStart);
                newWeekStart.setDate(newWeekStart.getDate() + 7);
                this.currentWeekStart = newWeekStart;  // 赋值新对象触发响应式
                this.loadSchedule();
            }
        },

        mounted() {
            this.initCurrentWeek();
            this.loadSchedule();
        }
    }).use(ElementPlus).mount('#app');
</script>
</body>
</html>